package com.heima.app.gateway.intercpiter;

import com.heima.app.gateway.until.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取请求参数
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求路劲,含有login则为登录请求
        String path = request.getURI().getPath();
        if (path.contains("login")) {
           return chain.filter(exchange);
        }
        //判断是否含有token
        String token = request.getHeaders().getFirst("token");
        //如果token为空
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
           return response.setComplete();
        }
        //如果token不为空
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int token1 = AppJwtUtil.verifyToken(claimsBody);

        try {
            if (token1 == 1 || token1 == 2) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
               return response.setComplete();
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
           return response.setComplete();
        }

        return chain.filter(exchange);
    }
}